package web

import (
	"encoding/json"
	"fmt"
	"github.com/jacktea/z-cron/web/action"
	"github.com/labstack/echo/v4"
	"io/ioutil"
	"net/http"
	"time"
)

type A struct {
	CreateTime time.Time `json:"createTime"`
	ActionTime time.Time `json:"actionTime"`
	AppId      string    `json:"appId"`
	TaskId     string    `json:"taskId"`
}

func InitRouter(e *echo.Echo, contextPath string) {
	group := e.Group(contextPath)
	// 状态监控
	group.GET("/info", func(c echo.Context) error {
		return c.String(http.StatusOK, "z-cron ")
	})
	group.GET("/health", func(c echo.Context) error {
		return c.String(http.StatusOK, "z-cron is ok")
	})

	group.POST("/print", func(c echo.Context) error {
		if b, err := ioutil.ReadAll(c.Request().Body); err != nil {
			return err
		} else {
			a := new(A)
			if err := json.Unmarshal(b, a); err == nil {
				fmt.Println(a.TaskId,
					a.CreateTime.Format("2006-01-02 15:04:05"),
					a.ActionTime.Format("2006-01-02 15:04:05"),
					time.Now().Format("2006-01-02 15:04:05"))
			}
			time.Sleep(time.Second * 1)
			return c.JSONBlob(http.StatusOK, b)
			//return c.String(http.StatusOK, "success")
		}
	})

	group.POST("/print1", func(c echo.Context) error {
		if b, err := ioutil.ReadAll(c.Request().Body); err != nil {
			return err
		} else {
			a := new(A)
			if err := json.Unmarshal(b, a); err == nil {
				fmt.Println(a.TaskId,
					a.CreateTime.Format("2006-01-02 15:04:05"),
					a.ActionTime.Format("2006-01-02 15:04:05"),
					time.Now().Format("2006-01-02 15:04:05"))
			}
			time.Sleep(time.Second * 1)
			return c.JSONBlob(http.StatusOK, b)
		}
	})

	// 任务管理接口
	apiGroup := group.Group("/api")
	apiGroup.POST("/addTask", action.AddTask)
	apiGroup.POST("/deleteTask", action.DeleteTask)
	apiGroup.POST("/getTask", action.GetTask)
	apiGroup.POST("/getTaskList", action.GetTaskList)
}
